/**
 * Copyright (C) 2004-2009 Jive Software. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.onlyxiahui.of.muc.iq;

import java.io.StringReader;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.PacketError;

import com.onlyxiahui.of.muc.dao.UserChatDAO;
import com.onlyxiahui.of.muc.data.Page;

public class IQUserChatLogHandler extends IQHandler {
	
	private static final Logger log = LoggerFactory.getLogger(IQUserChatLogHandler.class);
	private IQHandlerInfo info;
	private String serverName;

	private static final String MODULE_NAME = "Chat Operate Handler";
	private static final String NAME_SPACE = "http://www.jivesoftware.org/protocol/userChat#log";
	private static final String NAME_KEY = "userChat";
	private static final SAXReader xmlReader = new SAXReader();

	static {
		xmlReader.setEncoding("UTF-8");
	}

	public IQUserChatLogHandler() {
		super(MODULE_NAME);
		info = new IQHandlerInfo(NAME_KEY, NAME_SPACE);
	}

	@Override
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ result = IQ.createResultIQ(packet);
		String userBareJid = packet.getFrom().toBareJID();// .getNode();
		JID fromJid = packet.getFrom();
		// JID toJid =packet.getTo();

		int pageNumber = 0;
		int pageSize = 0;
		String value = null;
		Element pe = packet.getElement();
		Element chat = pe.element("userChat");
		if (null != chat) {
			Element n = chat.element("value");
			if (null != n) {
				value = n.getText();
			}
			Element page = chat.element("page");
			if (null != page) {
				String number = page.attributeValue("pageNumber");
				String size = page.attributeValue("pageSize");
				if (null != number && !number.isEmpty()) {
					pageNumber = Integer.parseInt(number);
				}
				if (null != size && !size.isEmpty()) {
					pageSize = Integer.parseInt(size);
				}
			}
		}
		boolean hasJid = (null != userBareJid && !userBareJid.isEmpty());

		if (!serverName.equals(packet.getFrom().getDomain()) || !hasJid) {
			result.setChildElement(packet.getChildElement().createCopy());
			result.setError(PacketError.Condition.not_allowed);
			return result;
		}
		Element chatLog = result.setChildElement(NAME_KEY, NAME_SPACE);

		String sJid = fromJid.toBareJID();
		String rJid = value;

		Page page = new Page();

		int totalCount = UserChatDAO.getMessageCount(sJid, rJid);
		page.setTotalCount(totalCount);
		page.setPageSize(pageSize);
		page.setPageNumber(pageNumber);

		int start = page.getStartResult();
		int count = page.getPageSize();
		Element pageElement = chatLog.addElement("page");
		pageElement.addAttribute("totalCount", page.getTotalCount() + "");
		pageElement.addAttribute("totalPage", page.getTotalPage() + "");
		pageElement.addAttribute("pageNumber", page.getPageNumber() + "");
		pageElement.addAttribute("pageSize", page.getPageSize() + "");

		Element messages = chatLog.addElement("messages");
		List<Map<String, String>> list = UserChatDAO.getUserMessageList(sJid, rJid, start, count);
		if (list != null && !list.isEmpty()) {
			for (Map<String, String> map : list) {

				String sendJid = map.get("sendJid");
				String receiveJid = map.get("receiveJid");
				String logTime = map.get("logTime");
				// String subject = map.get("subject");
				String body = map.get("body");
				String stanza = map.get("stanza");

				String messageId = "";

				if (null != stanza && !stanza.isEmpty()) {
					try {
						Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
						Message message = new Message(element);
						messageId = message.getID();
					} catch (DocumentException e) {
						// e.printStackTrace();
						log.error("", e);
					}
				}
				Element message = messages.addElement("message");
				message.addAttribute("messageId", messageId);
				message.addAttribute("from", sendJid);
				message.addAttribute("to", receiveJid);
				message.addAttribute("logTime", logTime);
				message.addElement("body").setText(body);
			}
		}
		//System.out.println(result);
		return result;
	}

	@Override
	public IQHandlerInfo getInfo() {
		return info;
	}

	@Override
	public void initialize(XMPPServer server) {
		super.initialize(server);
		serverName = server.getServerInfo().getXMPPDomain();
	}
}
